if (!jsx3.lang.Class.forName("ux.cdb.admin.queries.contract.Query")) {
    
jsx3.Class.defineClass(
    "ux.cdb.admin.queries.contract.Query", jsx3.gui.Block, [],
    function (query) {

        query.PAGE_SIZE  = 20;

        /**
         * Helper Functions, return a copy function with 
         * @param fn {Function}
         * @param scope {Object} 
         */
        query.prototype.bind = function(fn, scope) {
            scope = scope || this;
            return function() {
                fn.apply(scope, arguments);
            };
        };
        
        /**
         * Add event to jsx Object
         * @param name {String} jsx object name or comma-splitted names
         * @param event {String} event name
         * @param fct {Function} event handler
         */
        query.prototype.on = function (name, event, fct) {
            var names = name.split(","), block=this;
            for(var i=0; i<names.length; i++) {
                block = block.get(names[i]);
            }
            block[event] = this.bind(fct);
        };

        query.prototype.initialize = function(){
		}
        query.prototype._initialize = function(){
			this.queryUtil = ux.cdb.admin.queries.QueryUtil;
            this.on("btnQuery", "onClick", this.doQuery);
            this.on("btnReset", "onClick", this.onReset);
            this.queryDetail = this.get('queryDetail');
            this.matrix = this.get('mtxMain');
            this.dialogs = [];
            this.matrix.onSelected = jsx3.makeCallback(this.matrixSelected, this);

            this.pagebar = this.get("blkPageWheel");
            this.pagebar.initialize();
            this.pagebar.bindWithMatrix(this, this.pageChangeHandler, this.matrix);
            var me = this;
			ux.cdb.admin.CommonCache.loadCache(['INTERNAL_ORG','GENERAL_APP_STATUS'], me,
				function(){
					var _cache = ux.cdb.admin.CommonCache.getInstance();
					me.get('fieldOfInternalOrgId').getChild(1).setSourceXML(_cache.getCache('CommonCache_INTERNAL_ORG'));
					me.get('fieldOfAppStatusCode').getChild(1).setSourceXML(_cache.getCache('CommonCache_GENERAL_APP_STATUS'));
					me.get('fieldOfCopperOrgId').getChild(1).setSourceXML(jsx3.xml.CDF.Document.newDocument().insertRecord(this.queryUtil.getDefaultOption()));
					me.get('fieldOfCopperOrgId').getChild(1).repaint();
					me.get('fieldOfInternalOrgId').getChild(1).repaint();
					me.get('fieldOfAppStatusCode').getChild(1).repaint();
				});
            setTimeout(function() {me.onReset();}, 100);
        };

        query.prototype.pageChangeHandler = function(msg) {
            this.curPage = (msg && msg.currentPageNumber) ? msg.currentPageNumber : (this.curPage || 1);
            this.doQuery(this.curPage);
        };

        query.prototype.getPageInfo = function(curPage, pageSize, count) {
            var totalPages = (count%pageSize>0)?(parseInt(count/pageSize, 10)+1):(count/pageSize);
            if(totalPages === 0){ totalPages = 1; }
            return {
                curPage       : curPage,
                pageSize      : pageSize,
                totalCount    : count,
                totalPages    : totalPages
            };
        };
		query.prototype.displayTip = function(passed) {
			if(!passed) {
				var tip = ux.megatron.Main.getServer().getDynamicProperty("@cdb@queries@TipUnFinished");
				this.get('_messageLable').setText(tip,true);
			} else {
				this.get('_messageLable').setText("",true);
			}
		};
		
        query.prototype.doQuery = function(curPage, pageSize){
			if(this.queryDetail.doValidate() !== null){
				this.displayTip(false);
				return;
			}else{
				this.displayTip(true);
			}
    
            curPage = curPage || 1;
            pageSize = pageSize || query.PAGE_SIZE;
            var data = this.queryDetail.getDataAsObject();
            var params = [
                    data.internalOrgId,	data.cooperOrgId,	data.appStartTime,	data.appEndTime,
					data.studentName,	data.certCode,		data.appBasicInfoId,data.appStatusCode,
                    curPage,			pageSize ];
/* @JSC :: begin DEBUG */
			jsx3.log('contract#doQuery params : ' + params);
/* @JSC :: end */
            ux.megatron.util.Dwr.callDwr("RetailInfoQueryUCC", "getStudentContractListByCondition", 
                params, this, function(o){
                    if (o !== null && typeof o == 'object') {
                        var recordCount = o.content.page.count;
                        var pageInfo = this.getPageInfo(curPage, pageSize, recordCount);
                        this.pagebar.setValue(pageInfo.curPage, pageInfo.totalPages, pageInfo.pageSize, pageInfo.totalCount);
                        var data = o.content.data;
                        this.setMatrixData(data);
                    }
                });
        };

        query.prototype.setMatrixData = function(data) {
            var item, i;
            if(data && data instanceof Array) {
                var tmpCDF = jsx3.xml.CDF.Document.newDocument();
                for(i=0; i<data.length; i++){
                    item = data[i];
                    tmpCDF.insertRecord(item,null,false).setAttribute('jsxid',(i+1));
                }
/* @JSC :: begin DEBUG */
                jsx3.log("Query#setMatrixData : cdf= " + tmpCDF);
/* @JSC :: end */
                this.matrix.setSourceXML(tmpCDF);
                this.matrix.repaintData();
            } else {
                jsx3.log('Query#setMatrixData cdf data of matrix:' + data);
            }
        };
        
        query.prototype.onReset = function(){
            var resetData = {
                internalOrgId:'',
                cooperOrgId:'',
                appStartTime:new Date(),
                appEndTime:new Date(),
                studentName:null,
                certCode:null,
                appBasicInfoId:null,
                appStatusCode:''
            };
            this.queryDetail.setDataByObject(resetData);
            this.queryDetail.repaint();
/* @JSC :: begin DEBUG */
            jsx3.log('contract#Reset#initialize');
/* @JSC :: end */
        };
		
		query.prototype.loadCooperOrgList = function(recordId){
			if(!recordId) return;
			var cooperOrgBox = this.get('fieldOfCopperOrgId').getChild(1);
			cooperOrgBox.clearXmlData();
			cooperOrgBox.setSourceXML(jsx3.xml.CDF.Document.newDocument().insertRecord({jsxid:'',jsxtext:'Loading...',jsxstyle:'width:100%;'}));
			cooperOrgBox.repaint();
			var option = [{
				dwrClass:'RetailInfoQueryUCC',
				dwrFunction:'getInitCooperOrg',
				dwrParams:[recordId]
			}];
			this.queryUtil.loadCustomizeCache(option, this, function(){
				var cdf = this.queryUtil.getInstance().getCacheAsCDF(0, {jsxid:'partyId', jsxtext:'chnFullName'});
				cooperOrgBox.setSourceXML(cdf);
				cooperOrgBox.repaint();
/* @JSC :: begin DEBUG */
				jsx3.log('loadCustomizeCache finished. cdf : ' + cdf);
/* @JSC :: end */
			});
/* @JSC :: begin DEBUG */
			jsx3.log('loadCooperOrgList recordId : ' + recordId);
/* @JSC :: end */
		};
        
        query.prototype.matrixSelected = function(mtx, strRECORDID){
            var parent = ux.megatron.Main.getServer().getBodyBlock();
            var rec = mtx.getRecord(strRECORDID);
            ux.megatron.Main.loadUIResourceAsync(parent,  
                "ux.cdb.admin","ux/cdb/admin/queries/contract/ui/detailDialog.xml", this,  this.dialogLoaded);
        };
        
        query.prototype.dialogLoaded = function(objEvent){
			var hiddenReceipt = false;
			var nodes = this.matrix.getSelectedNodes();
			jsx3.log('Query#dialogLoaded nodes : ' + nodes);
			if(nodes.size() == 1) {
				hiddenReceipt = (nodes.get(0).getAttribute("code") == "03");
				//TODO:: Load Data into TabedPane
				var appBasicInfoId = nodes.get(0).getAttribute("appBasicInfoId");
				var studentId = nodes.get(0).getAttribute("studentId");
				jsx3.log('objEvent.obj.count : ' + objEvent.obj.count);
				objEvent.obj.detailInfo = {"Contract": appBasicInfoId, "Receipt":appBasicInfoId, Loan: appBasicInfoId, "Student": studentId};
				objEvent.obj.hiddenReceipt = hiddenReceipt;
				//objEvent.obj.loadContractDetail({"Contract": appBasicInfoId, "Receipt":appBasicInfoId, Loan: appBasicInfoId, "Student": studentId}, hiddenReceipt);
			}
			
            //objEvent.obj.repaint();
			
            this.dialogs.push(objEvent.obj);
        };

        query.prototype.onDestroy = function() {
            for(var i=0; i<this.dialogs.length; i++) {
                if(this.dialogs[i].getServer()) {
                    this.dialogs[i].doClose();
                }
            }
        };
    });
}